<template>
  <view class="order-create-page">
    <!-- 课程信息 -->
    <view class="course-card">
      <view class="course-info">
        <image :src="courseInfo.coverUrl" class="course-image" mode="aspectFill" />
        <view class="course-details">
          <text class="course-title">{{ courseInfo.title }}</text>
          <text class="course-desc">{{ courseInfo.description }}</text>
          <view class="course-price">
            <text class="current-price">¥{{ courseInfo.currentPrice }}</text>
            <text v-if="courseInfo.originalPrice > courseInfo.currentPrice" class="original-price">
              ¥{{ courseInfo.originalPrice }}
            </text>
          </view>
        </view>
      </view>
      
      <view class="quantity-selector">
        <text class="quantity-label">数量</text>
        <view class="quantity-controls">
          <button class="quantity-btn" @click="decreaseQuantity" :disabled="quantity <= 1">-</button>
          <text class="quantity-value">{{ quantity }}</text>
          <button class="quantity-btn" @click="increaseQuantity">+</button>
        </view>
      </view>
    </view>

    <!-- 联系信息 -->
    <view class="contact-card">
      <view class="card-title">联系信息</view>
      <view class="form-item">
        <text class="form-label">联系人</text>
        <input 
          v-model="contactInfo.name"
          class="form-input"
          placeholder="请输入联系人姓名"
          maxlength="20"
        />
      </view>
      <view class="form-item">
        <text class="form-label">联系电话</text>
        <input 
          v-model="contactInfo.phone"
          class="form-input"
          placeholder="请输入联系电话"
          type="number"
          maxlength="11"
        />
      </view>
      <view class="form-item">
        <text class="form-label">备注信息</text>
        <textarea 
          v-model="contactInfo.remark"
          class="form-textarea"
          placeholder="请输入备注信息（选填）"
          maxlength="200"
        />
      </view>
    </view>

    <!-- 优惠券 -->
    <view class="coupon-card" @click="selectCoupon">
      <view class="coupon-info">
        <text class="coupon-label">优惠券</text>
        <text class="coupon-value" v-if="selectedCoupon">
          {{ selectedCoupon.name }} -¥{{ selectedCoupon.discountAmount }}
        </text>
        <text class="coupon-placeholder" v-else>选择优惠券</text>
      </view>
      <text class="coupon-arrow">></text>
    </view>

    <!-- 价格明细 -->
    <view class="price-card">
      <view class="card-title">价格明细</view>
      <view class="price-list">
        <view class="price-item">
          <text class="price-label">课程价格</text>
          <text class="price-value">¥{{ courseInfo.currentPrice }}</text>
        </view>
        <view class="price-item">
          <text class="price-label">数量</text>
          <text class="price-value">{{ quantity }}</text>
        </view>
        <view class="price-item">
          <text class="price-label">小计</text>
          <text class="price-value">¥{{ subtotal }}</text>
        </view>
        <view class="price-item" v-if="discountAmount > 0">
          <text class="price-label">优惠金额</text>
          <text class="price-value discount">-¥{{ discountAmount }}</text>
        </view>
        <view class="price-item total">
          <text class="price-label">实付金额</text>
          <text class="price-value">¥{{ totalAmount }}</text>
        </view>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-card">
      <view class="card-title">支付方式</view>
      <view class="payment-methods">
        <view 
          v-for="method in paymentMethods" 
          :key="method.value"
          class="payment-method"
          :class="{ active: selectedPayment === method.value }"
          @click="selectPayment(method.value)"
        >
          <image :src="method.icon" class="payment-icon" />
          <text class="payment-name">{{ method.name }}</text>
          <text class="payment-check" v-if="selectedPayment === method.value">✓</text>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-actions">
      <view class="total-info">
        <text class="total-label">实付金额</text>
        <text class="total-amount">¥{{ totalAmount }}</text>
      </view>
      <button class="submit-btn" @click="submitOrder" :loading="submitting">
        {{ submitting ? '提交中...' : '提交订单' }}
      </button>
    </view>

    <!-- 优惠券选择弹窗 -->
    <view class="modal-overlay" v-if="showCouponModal" @click="hideCouponModal">
      <view class="modal-content" @click.stop>
        <view class="modal-header">
          <text class="modal-title">选择优惠券</text>
          <text class="modal-close" @click="hideCouponModal">×</text>
        </view>
        
        <view class="coupon-list">
          <view 
            class="coupon-item"
            :class="{ active: !selectedCoupon }"
            @click="selectCouponItem(null)"
          >
            <text class="coupon-name">不使用优惠券</text>
            <text class="coupon-check" v-if="!selectedCoupon">✓</text>
          </view>
          
          <view 
            v-for="coupon in availableCoupons" 
            :key="coupon.id"
            class="coupon-item"
            :class="{ active: selectedCoupon?.id === coupon.id, disabled: !coupon.available }"
            @click="selectCouponItem(coupon)"
          >
            <view class="coupon-content">
              <text class="coupon-name">{{ coupon.name }}</text>
              <text class="coupon-desc">{{ coupon.description }}</text>
              <text class="coupon-condition">{{ coupon.condition }}</text>
            </view>
            <view class="coupon-amount">
              <text class="amount-symbol">¥</text>
              <text class="amount-value">{{ coupon.discountAmount }}</text>
            </view>
            <text class="coupon-check" v-if="selectedCoupon?.id === coupon.id">✓</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import Taro, { useRouter } from '@tarojs/taro'
import courseApi from '@/api/course'
import orderApi from '@/api/order'
import { showLoading, hideLoading, showError, showSuccess, validatePhone } from '@/utils'

// 路由参数
const router = useRouter()
const { courseId, merchantId } = router.params

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const courseInfo = ref({})
const quantity = ref(1)
const contactInfo = ref({
  name: '',
  phone: '',
  remark: ''
})

const selectedCoupon = ref(null)
const selectedPayment = ref('wxpay')
const showCouponModal = ref(false)
const availableCoupons = ref([])

// 支付方式
const paymentMethods = ref([
  {
    name: '微信支付',
    value: 'wxpay',
    icon: '/static/images/wxpay.png'
  }
])

// 计算属性
const subtotal = computed(() => {
  return (courseInfo.value.currentPrice * quantity.value).toFixed(2)
})

const discountAmount = computed(() => {
  if (!selectedCoupon.value) return 0
  return selectedCoupon.value.discountAmount
})

const totalAmount = computed(() => {
  const total = subtotal.value - discountAmount.value
  return Math.max(0, total).toFixed(2)
})

// 页面加载
onMounted(() => {
  if (courseId) {
    loadCourseInfo()
    loadAvailableCoupons()
    loadUserInfo()
  }
})

// 加载课程信息
const loadCourseInfo = async () => {
  try {
    loading.value = true
    showLoading('加载中...')
    
    const result = await courseApi.getCourseDetail(courseId)
    
    if (result.code === 200) {
      courseInfo.value = result.data
    } else {
      showError(result.msg || '加载失败')
    }
  } catch (error) {
    console.error('加载课程信息失败:', error)
    showError('加载失败，请重试')
  } finally {
    loading.value = false
    hideLoading()
  }
}

// 加载可用优惠券
const loadAvailableCoupons = async () => {
  try {
    const result = await orderApi.getAvailableCoupons({
      courseId,
      merchantId,
      amount: subtotal.value
    })
    
    if (result.code === 200) {
      availableCoupons.value = result.data || []
    }
  } catch (error) {
    console.error('加载优惠券失败:', error)
  }
}

// 加载用户信息
const loadUserInfo = async () => {
  try {
    const userInfo = Taro.getStorageSync('userInfo')
    if (userInfo) {
      contactInfo.value.name = userInfo.nickName || ''
      contactInfo.value.phone = userInfo.phonenumber || ''
    }
  } catch (error) {
    console.error('加载用户信息失败:', error)
  }
}

// 增加数量
const increaseQuantity = () => {
  quantity.value++
  // 重新计算优惠券
  loadAvailableCoupons()
}

// 减少数量
const decreaseQuantity = () => {
  if (quantity.value > 1) {
    quantity.value--
    // 重新计算优惠券
    loadAvailableCoupons()
  }
}

// 选择优惠券
const selectCoupon = () => {
  showCouponModal.value = true
}

// 隐藏优惠券弹窗
const hideCouponModal = () => {
  showCouponModal.value = false
}

// 选择优惠券项
const selectCouponItem = (coupon) => {
  if (coupon && !coupon.available) return
  
  selectedCoupon.value = coupon
  showCouponModal.value = false
}

// 选择支付方式
const selectPayment = (method) => {
  selectedPayment.value = method
}

// 表单验证
const validateForm = () => {
  if (!contactInfo.value.name.trim()) {
    showError('请输入联系人姓名')
    return false
  }
  
  if (!contactInfo.value.phone.trim()) {
    showError('请输入联系电话')
    return false
  }
  
  if (!validatePhone(contactInfo.value.phone)) {
    showError('请输入正确的手机号码')
    return false
  }
  
  return true
}

// 提交订单
const submitOrder = async () => {
  if (!validateForm()) return
  
  try {
    submitting.value = true
    showLoading('提交中...')
    
    const orderData = {
      courseId,
      merchantId,
      quantity: quantity.value,
      contactInfo: contactInfo.value,
      couponId: selectedCoupon.value?.id,
      paymentMethod: selectedPayment.value,
      totalAmount: totalAmount.value,
      discountAmount: discountAmount.value
    }
    
    const result = await orderApi.createOrder(orderData)
    
    if (result.code === 200) {
      const orderId = result.data.orderId
      
      showSuccess('订单创建成功')
      
      // 跳转到订单详情页
      setTimeout(() => {
        Taro.redirectTo({
          url: `/pages/order/detail?id=${orderId}`
        })
      }, 1500)
    } else {
      showError(result.msg || '订单创建失败')
    }
  } catch (error) {
    console.error('提交订单失败:', error)
    showError('提交失败，请重试')
  } finally {
    submitting.value = false
    hideLoading()
  }
}
</script>

<style lang="less">
.order-create-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-bottom: 120px;
}

.course-card,
.contact-card,
.coupon-card,
.price-card,
.payment-card {
  background: white;
  margin-bottom: 16px;
  padding: 32px;

  .card-title {
    font-size: 32px;
    font-weight: 600;
    color: #333;
    margin-bottom: 24px;
  }
}

.course-info {
  display: flex;
  margin-bottom: 24px;

  .course-image {
    width: 160px;
    height: 120px;
    border-radius: 12px;
    flex-shrink: 0;
  }

  .course-details {
    flex: 1;
    margin-left: 24px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;

    .course-title {
      font-size: 28px;
      font-weight: 500;
      color: #333;
      margin-bottom: 8px;
      line-height: 1.4;
    }

    .course-desc {
      font-size: 24px;
      color: #666;
      line-height: 1.4;
      margin-bottom: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
    }

    .course-price {
      display: flex;
      align-items: baseline;
      gap: 16px;

      .current-price {
        font-size: 32px;
        font-weight: 600;
        color: #F5A623;
      }

      .original-price {
        font-size: 24px;
        color: #999;
        text-decoration: line-through;
      }
    }
  }
}

.quantity-selector {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .quantity-label {
    font-size: 28px;
    color: #333;
  }

  .quantity-controls {
    display: flex;
    align-items: center;
    gap: 24px;

    .quantity-btn {
      width: 60px;
      height: 60px;
      border: 1px solid #e0e0e0;
      border-radius: 8px;
      background: white;
      font-size: 32px;
      color: #333;
      display: flex;
      align-items: center;
      justify-content: center;

      &:disabled {
        color: #ccc;
        border-color: #f0f0f0;
      }
    }

    .quantity-value {
      font-size: 28px;
      color: #333;
      min-width: 40px;
      text-align: center;
    }
  }
}

.form-item {
  margin-bottom: 24px;

  .form-label {
    font-size: 28px;
    color: #333;
    display: block;
    margin-bottom: 16px;
  }

  .form-input {
    width: 100%;
    height: 80px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 0 24px;
    font-size: 28px;
    background: #f8f9fa;
  }

  .form-textarea {
    width: 100%;
    min-height: 120px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    padding: 24px;
    font-size: 28px;
    background: #f8f9fa;
    resize: none;
  }
}

.coupon-card {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .coupon-info {
    flex: 1;

    .coupon-label {
      font-size: 28px;
      color: #333;
      display: block;
      margin-bottom: 8px;
    }

    .coupon-value {
      font-size: 24px;
      color: #F5A623;
      display: block;
    }

    .coupon-placeholder {
      font-size: 24px;
      color: #999;
      display: block;
    }
  }

  .coupon-arrow {
    font-size: 32px;
    color: #ccc;
  }
}

.price-list {
  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    .price-label {
      font-size: 28px;
      color: #666;
    }

    .price-value {
      font-size: 28px;
      color: #333;

      &.discount {
        color: #52C41A;
      }
    }

    &.total {
      border-top: 1px solid #f0f0f0;
      padding-top: 24px;
      margin-top: 8px;

      .price-label {
        font-weight: 600;
        color: #333;
      }

      .price-value {
        font-size: 32px;
        font-weight: 600;
        color: #F5A623;
      }
    }
  }
}

.payment-methods {
  .payment-method {
    display: flex;
    align-items: center;
    padding: 24px 0;
    border-bottom: 1px solid #f0f0f0;

    &:last-child {
      border-bottom: none;
    }

    &.active {
      .payment-name {
        color: #3478F6;
      }
    }

    .payment-icon {
      width: 48px;
      height: 48px;
      margin-right: 24px;
    }

    .payment-name {
      flex: 1;
      font-size: 28px;
      color: #333;
    }

    .payment-check {
      font-size: 28px;
      color: #3478F6;
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 24px 32px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .total-info {
    .total-label {
      font-size: 24px;
      color: #666;
      display: block;
    }

    .total-amount {
      font-size: 36px;
      font-weight: 600;
      color: #F5A623;
      display: block;
    }
  }

  .submit-btn {
    background: #3478F6;
    color: white;
    border: none;
    border-radius: 32px;
    padding: 24px 48px;
    font-size: 32px;
    font-weight: 600;
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;

  .modal-content {
    background: white;
    width: 90%;
    max-height: 80vh;
    border-radius: 16px;
    overflow: hidden;

    .modal-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 32px;
      border-bottom: 1px solid #f0f0f0;

      .modal-title {
        font-size: 32px;
        font-weight: 600;
        color: #333;
      }

      .modal-close {
        font-size: 48px;
        color: #999;
      }
    }

    .coupon-list {
      max-height: 60vh;
      overflow-y: auto;

      .coupon-item {
        display: flex;
        align-items: center;
        padding: 32px;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        &.active {
          background: #f0f8ff;
        }

        &.disabled {
          opacity: 0.5;
        }

        .coupon-content {
          flex: 1;

          .coupon-name {
            font-size: 28px;
            color: #333;
            display: block;
            margin-bottom: 8px;
          }

          .coupon-desc {
            font-size: 24px;
            color: #666;
            display: block;
            margin-bottom: 4px;
          }

          .coupon-condition {
            font-size: 20px;
            color: #999;
            display: block;
          }
        }

        .coupon-amount {
          display: flex;
          align-items: baseline;
          margin-right: 24px;

          .amount-symbol {
            font-size: 24px;
            color: #F5A623;
          }

          .amount-value {
            font-size: 36px;
            font-weight: 600;
            color: #F5A623;
          }
        }

        .coupon-check {
          font-size: 28px;
          color: #3478F6;
        }
      }
    }
  }
}
</style>